package com.ethink.framework.common.exception;

import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.constant.ResponseCodeEnum;

/**
 * 业务异常
 *
 * @author yunduo
 */
public class BusinessException extends RuntimeException {

    /**
     * 响应码枚举
     */
    private ResponseCodeEnum codeEnum;

    /**
     * 响应码
     */
    private String code;

    /**
     * 响应信息
     */
    private String codeMessage;

    /**
     * 无参构造方法,返回系统异常
     */
    public BusinessException() {
        this(CommonRespCode.SYSTEM_ERR);
    }

    /**
     * @param codeEnum 响应码
     */
    public BusinessException(ResponseCodeEnum codeEnum) {
        super(codeEnum.getCode() + "," + codeEnum.getMessage());
        this.code = codeEnum.getCode();
        this.codeMessage = codeEnum.getMessage();
        this.codeEnum = codeEnum;
    }

    /**
     * 通过code,自定义message创建异常
     *
     * @param code
     * @param codeMessage
     */
    public BusinessException(String code, String codeMessage) {
        super(code + "," + codeMessage);
        this.code = code;
        this.codeMessage = codeMessage;
        this.codeEnum = new UndefinedResponseCodeEnum(code, codeMessage);
    }

    /**
     * 通过ResponseCodeEnum,自定义message创建异常
     *
     * @param codeEnum
     * @param codeMessage
     */
    public BusinessException(ResponseCodeEnum codeEnum, String codeMessage) {
        super(codeEnum.getCode() + "," + codeMessage);
        this.code = codeEnum.getCode();
        this.codeMessage = codeMessage;
        this.codeEnum = codeEnum;
    }

    /**
     * @param codeEnum 响应码
     * @param e        异常
     */
    public BusinessException(ResponseCodeEnum codeEnum, Throwable e) {
        super(e);
        this.code = codeEnum.getCode();
        this.codeMessage = codeEnum.getMessage();
        this.codeEnum = codeEnum;
    }

    /**
     * 获取响应码枚举
     *
     * @return
     */
    public ResponseCodeEnum getCodeEnum() {
        return codeEnum;
    }

    /**
     * 获取响应码
     * @return
     */
    public String getCode() {
        return code;
    }

    /**
     * 响应信息
     * @return
     */
    public String getCodeMessage() {
        return codeMessage;
    }

    public static class UndefinedResponseCodeEnum implements ResponseCodeEnum {

        /**
         * 响应码
         */
        private String code;

        /**
         * 响应描述
         */
        private String message;

        public UndefinedResponseCodeEnum(String code, String message) {
            this.code = code;
            this.message = message;
        }

        @Override
        public String getCode() {
            return this.code;
        }

        @Override
        public String getMessage() {
            return this.message;
        }
    }
}
